﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Marmat.Common.Http
{
    /// <summary>
    /// 表示Http响应的文件 可以声明为接口的返回类型
    /// </summary>
    public class HttpResponseFile : HttpResponseMessage
    {
        public HttpResponseFile(HttpWebResponse httpResponse) : base(httpResponse)
        {
        }

        /// <summary>
        /// 保存到指定路径
        /// </summary>
        /// <param name="filePath">文件路径和文件名</param>
        public async Task SaveAsAsync(string filePath)
        {
            using System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
            await this.SaveAsAsync(stream);
        }

        /// <summary>
        /// 保存到指定流
        /// </summary>
        /// <param name="stream"></param>
        public async Task SaveAsAsync(Stream stream)
        {
            await Task.Run(() =>
             {
                 using System.IO.Stream resStream = this.HttpResponse.GetResponseStream();
                 byte[] bArr = new byte[1024];
                 int size = resStream.Read(bArr, 0, bArr.Length);
                 while (size > 0)
                 {
                     stream.Write(bArr, 0, size);
                     size = resStream.Read(bArr, 0, bArr.Length);
                 }
                 stream.Close();
                 resStream.Close();
             });
        }
    }
}
